#include<stdio.h>
#include <stdlib.h>
#include <stdbool.h>

//stack
typedef int SElemType_t;

typedef struct  node
{
    SElemType_t data;
    struct node *next;
}Node_t;

Node_t *head;

//list_init
void stack_init()
{
    //1 申请头节点
    head = malloc(sizeof(Node_t));

    head->next = NULL;
}

//入栈  插入数据  尾插
void push(SElemType_t data)
{
    //1 新建一个结点并且初始化
    Node_t *newNode  = malloc(sizeof(Node_t));
    
    newNode->data = data;
    newNode->next = NULL;
    
    //2 尾插
    if(head->next == NULL){
        head->next = newNode;
    }else{
        //找到尾节点
        Node_t *p = head->next;
        while (1)
        {
            if(p->next == NULL)
                break;

            p = p->next;
        }

        p->next = newNode;
        
    }
}

bool isEmpty()
{
    return head->next == NULL;
}

//出栈  删除数据  尾删   为何出栈？？？？ 就是要对数据利用
bool pop(SElemType_t *data)
{
    //1 先判断栈是否是空的
    if(isEmpty())
        return false;
    //2 找到尾节点
    Node_t *p = head->next;
    Node_t *pre = head;

    while (1)
    {
        if(p->next == NULL)
            break;

        pre = p;
        p = p->next;
    }

    //先把数据存下来
    *data = p->data;
    free(p);
    pre->next = NULL;

    return true;
}



int main()
{
    stack_init();
    push(10);
    push(20);
    push(30);
    push(40);

    while (1)
    {
        /* code */
        SElemType_t data;
        bool ret = pop(&data);
        if(ret == false){
            break;
        }
        printf("%d\n",data);
    }
    

    return 0;
}